package blackpai.backend.controller;


import blackpai.backend.util.SecurityCode;
import blackpai.backend.util.SecurityImage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
@RequestMapping("verifycode")
public class CodeController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("getVerifyCode")
    public String getCode(HttpServletRequest request, HttpServletResponse response)throws IOException{
        //设置相应类型
        response.setContentType("image/png");
        //获取验证码
        String securityCode = SecurityCode.getSecurityCode();
        //生成验证码图片
        BufferedImage image = SecurityImage.createImage(securityCode);
        //存入session
        request.getSession().setAttribute("securityCode",securityCode);
        //存入redis
        String forObject = restTemplate.getForObject("http://redis-server/redis/setVerifyCode?verifycode="+securityCode, String.class);
        ImageIO.write(image, "png", response.getOutputStream());
        return "";
    }
}
